﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Entity;
using CodeFirstDemo.Model;

namespace CodeFirstDemo.Data
{
    public class CodeFirstDBContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }

        //public DbSet<User> Users { get; set; }
        public DbSet<Address> Addresses { get; set; }
        public DbSet<Shipment> Shipments { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //base.OnModelCreating(modelBuilder);
            // 指定 Category 的主键
            modelBuilder.Entity<Category>().HasKey(c => c.CategoryCode);

            // 从Product指定外键关联
            modelBuilder.Entity<Product>()
                .HasRequired(p => p.PrimaryCategory)
                .WithMany(c => c.Products)
                .HasForeignKey(p => p.PrimaryCategoryCode);// 如果不打算使用指定的外键，EFCodeFirst会自己创建一个：导航属性名_关联表的主键名

            // 从Category指定外键关联
            modelBuilder.Entity<Category>()
                .HasMany(c => c.Products)
                .WithRequired(p => p.PrimaryCategory)
                .HasForeignKey(p => p.PrimaryCategoryCode);

            // 以上两个仅仅 执行一种就可，如果两个都执行，EF会自动忽略其中一个。


            modelBuilder.Entity<User>().HasOptional(u => u.BillingAddress)
                               .WithRequired();

            modelBuilder.Entity<Shipment>().HasRequired(u => u.DeliveryAddress)
                                           .WithOptional();
        }
    }
}



//internal bool ModelIsValid(TModel view)
//        {
//            ErrorMessages = new List<string>();
//            foreach (var property in typeof(TModel).GetProperties())
//            {
//                var value = property.GetValue(view, null);

//                var attributes = property.GetCustomAttributes(typeof(IValidationAttribute), false);
//                foreach (IValidationAttribute valatt in attributes)
//                    if (!valatt.IsValid(value))
//                        ErrorMessages.Add(valatt.Message);
//            }

//            return ErrorMessages.Count == 0;
//        }
